package com.balance.anole.erp;

import org.eclipse.core.runtime.Platform;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.balance.anole.client.common.service.CommonService;
import com.balance.anole.erp.security.login.view.LoginDialog;
import com.balance.anole.erp.util.ServicesCenter;

/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IApplication {

	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
	 */
	public Object start(IApplicationContext context) {
		Display display = PlatformUI.createDisplay();
		try {
			ApplicationContext springCtx = new ClassPathXmlApplicationContext(new String[] {"services-remote.xml", "services-local.xml"});
			Platform.endSplash();
			Boolean loginSuccessful = login();
			if(loginSuccessful != null && loginSuccessful){
				synchronizeWithServer();
				int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
				if (returnCode == PlatformUI.RETURN_RESTART) {
					return IApplication.EXIT_RESTART;
				}
			}
			return IApplication.EXIT_OK;
		} finally {
			display.dispose();
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#stop()
	 */
	public void stop() {
		final IWorkbench workbench = PlatformUI.getWorkbench();
		if (workbench == null)
			return;
		final Display display = workbench.getDisplay();
		display.syncExec(new Runnable() {
			public void run() {
				if (!display.isDisposed())
					workbench.close();
			}
		});
	}

	private void synchronizeWithServer(){
		//synchronize business date
		CommonService cs = ServicesCenter.getServicesCenter().getService(CommonService.class);
		boolean warning = cs.synchronizeBusinessDate();
		if(warning){
			MessageDialog.openWarning(Display.getDefault().getActiveShell(), "同步", "日期同步不成功，请检查系统日期或者联系代理商.");
		}
		//TODO: synchronize reference data
	}

	private Boolean login() {
		LoginDialog loginDialog = new LoginDialog(null);
		Boolean loginSuccessful = false;
		if (loginDialog.open() != Window.OK) {
			loginSuccessful = null;
		}else{
			loginSuccessful = true;
		}
		return loginSuccessful;
	}
}
